package com.crazy.cloud.common.advice;

import com.crazy.cloud.common.api.ApiResponse;
import com.crazy.cloud.common.exception.DataConflictException;
import com.crazy.cloud.common.exception.DataNotFoundException;
import com.crazy.cloud.common.exception.IllegalOperationException;
import com.crazy.cloud.common.exception.UnavailableServiceException;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @program: crazy-cloud
 * @description: 异常处理handler
 * @author: CrazyMan
 * @create: 2018/9/25 下午4:38
 **/
@Slf4j
@RestControllerAdvice
public class DefaultExceptionHandler {

    @ExceptionHandler(DataNotFoundException.class)
    public ApiResponse dataNotFound(DataNotFoundException e) {
        return ApiResponse.error(20404, StringUtils.isEmpty(e.getMessage()) ? "没有相关信息" : e.getMessage());
    }

    @ExceptionHandler(IllegalArgumentException.class)
    public ApiResponse illegalArgumentException(IllegalArgumentException e) {
        log.warn("参数错误：" + e.getMessage());
        return ApiResponse.error(40035, StringUtils.isEmpty(e.getMessage()) ? "参数错误！" : e.getMessage());
    }

    @ExceptionHandler(DataConflictException.class)
    public ApiResponse repeatSubmit(DataConflictException e) {
        log.warn("重复提交信息: {}", e.getMessage());
        return ApiResponse.error(40409, StringUtils.isEmpty(e.getMessage()) ? "数据已存在！" : e.getMessage());
    }

    @ExceptionHandler(IllegalOperationException.class)
    public ApiResponse illegalOperate(IllegalOperationException e) {
        log.warn("非法操作：{}", e.getMessage());
        return ApiResponse.error(40412, StringUtils.isEmpty(e.getMessage()) ? "非法操作！" : e.getMessage());
    }

    @ExceptionHandler(UnavailableServiceException.class)
    public ApiResponse illegalOperate(UnavailableServiceException e) {
        log.warn("非法操作：{}", e.getMessage());
        return ApiResponse.error(50500, StringUtils.isEmpty(e.getMessage()) ? "服务不可用！" : e.getMessage());
    }

    @ExceptionHandler(Throwable.class)
    public ApiResponse serverError(Throwable e, HttpServletRequest request) {
        log.error("服务器内部错误,message:{},accessUrl:{},referer:{}", e.getMessage(), request.getRequestURI(), request.getHeader("referer"), e);
        return ApiResponse.error(500, "系统繁忙！");
    }


}
